package cn.gson.crm.controller.teaching;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.BedRoomDao;
import cn.gson.crm.model.dao.ClassDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.entity.BedRoom;
import cn.gson.crm.model.entity.Classes;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.mapper.BedroomMapper;

/**
 * 
 * @author GHOST
 *
 */
@Controller
@RequestMapping("/bedroom")
public class BedRoomController {

	@Autowired
	private BedroomMapper brm;
	
	
	@Autowired
	private BedRoomDao brd;

	@Autowired
	private ClassDao classdao;
	
	@Autowired
	private StudentDao stud;
	
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> index(
			BedRoom br, 
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<BedRoom> pageData = brm.list(br);

		PageInfo<BedRoom> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	Map<String,Object> stuobj = new HashMap<String, Object>();
	
	List<Student> studfb = new ArrayList<Student>();
	
	Long tags;
	/**
	 * 查询所有待分寝的学员
	 * @param br
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("studentlist/{gender}")
	@ResponseBody
	public Map<String, Object> studentlist(
			@PathVariable("gender") String gender,
			Student student) {
		Map<String, Object> obj = new HashMap<String, Object>();
		List<Student> stu = brm.selectNoDormStudentes(gender);
		if(stuobj.size() != 0 && studfb != null) {
			stu.removeAll(studfb);
		}
		
		obj.put("total", stu.size());
		obj.put("rows",stu);
		
		return obj;
	}

	
	/**
	 * 删除寝室
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public Map<String, Object> delete(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		BedRoom bedroom;
		Student student;
		if (id != null && (bedroom = brd.findOne(id)) != null) {
			if(bedroom.getStudentId()!=null) {
				 student=stud.findOne(bedroom.getStudentId().getId());
				//先修改上一个寝室长
				 student.setDormitory(false);
				 stud.save(student);
				}
			bedroom.setDelete(0L);
			bedroom.setCount(0L);
			bedroom.setStudentId(null);
			bedroom.setState("空余");
			//删除该寝室的所有学员
			brm.deleteAllStudent(id);
			
			brd.save(bedroom);
			obj.put("success", true);
		} else {
			obj.put("message", "抱歉，没有该寝室");
		}
		return obj;
	}
	
	

	/**
	 * 打开添加寝室界面
	 * @param model
	 * @return
	 */
	@GetMapping({ "addbedroom", "addbedroom/{id}" })
	public String form(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			// 根据Id查询就业学员的反馈信息
			BedRoom bedroom = brd.findOne(id);
			// 查询所有就业学员的姓名和id
			if (bedroom != null) {
				// 如果是编辑，则把原有用户信息传回表单页面
				model.addAttribute("bedroom", bedroom);
			}
		}
		List<Map<String, Object>> stu = brm.studentGenderListById(id);
		model.addAttribute("students", stu);
		return "bedroom/addbedroom";
	}

	/**
	 * 添加寝室和编辑寝室
	 * @param bedroom
	 * @param br
	 * @return
	 */
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public Map<String,Object> save(
			BedRoom bedroom, 
			BindingResult br) {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "添加失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			int count=brm.countBedroomName(bedroom.getName());
			if(bedroom.getId()==null) {
				if (count>=1) {
						obj.put("message", "该寝室已存在");
						return obj;
					}
			}
				bedroom.setDelete(1L);
				//判断是否为添加
			if (bedroom.getId() != null) {
				if (count>1) {
					obj.put("message", "该寝室已存在");
					return obj;
				}
				
				if(bedroom.getCount()==bedroom.getBed()) {
					bedroom.setState("住满");
				}else if(bedroom.getCount()<bedroom.getBed()){
					bedroom.setState("空余");
				}
				
				bedroom.setCount(bedroom.getCount());
				brm.editBedRoom(bedroom);
				
			}else {
				bedroom.setCount(0L);
				bedroom.setState("空余");
				brd.save(bedroom);
				
			}
			
			obj.put("success", true);
		}
		return obj;
	}


	
	/**
	 * 查询寝室id和寝室详情信息
	 * @param model
	 * @return
	 */
	@GetMapping("bedroom_details/{id}")
	public String bedroom_details(
			@PathVariable(name = "id", required = false) 
			Long id,
			Model model) {
			BedRoom bedroom = brd.findOne(id);
			model.addAttribute("bedroom", bedroom);
		
			return "bedroomDetails/bedroom_details";
	}
	
	/**
	 * 打开寝室添加学员页面
	 * @param student
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("addsutdent/{id}")
	public String addsutdent(Student student,@PathVariable(name = "id", required = false) Long id,Model model) {
		BedRoom bedroom = brm.selectIdbedroommessage(id);
		
		Iterable<Classes> classes = classdao.findAll();
		
		List<Student> stu = brm.selectNoDormStudents();
 		int male=0;
		int female=0;
		for(int i = 0;i<stu.size();i++) {
			if(stu.get(i).getGender().equals("男")) {
				male++;
			}else if(stu.get(i).getGender().equals("女")){
				female++;
			}
		}
		model.addAttribute("studentSize", stu.size());
		model.addAttribute("male", male);
		model.addAttribute("female", female);
		
		model.addAttribute("bedroom", bedroom);
		model.addAttribute("classes", classes);
		return "bedroom/addsutdent";
	}

	
	/**
	 * 为寝室添加学员
	 * @param id
	 * @param ids
	 * @return
	 */
	@RequestMapping("savebedroomstu/{id}/{ids}/{xz}")
	@ResponseBody
	@Transactional
	public Map<String, Object> savebedroomstu(
			@PathVariable(name = "id", required = false) Long id,
			@PathVariable(name = "xz", required = false) Long xz,
			@PathVariable(name = "ids", required = false) Long[] ids){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		
		Map<String, Object> saveParams = new HashMap<>();
		saveParams.put("dormitoryId", id);
		saveParams.put("stuId", Arrays.asList(ids));
		
		BedRoom b = brd.findOne(id);
		for (int i = 0; i < ids.length; i++) {
			if(xz==b.getBed()) {
				b.setState("住满");
			}
				b.setCount(b.getCount() + 1);
				brd.save(b);
			
		}
		obj.put("success", true);
		// 在中间表添加一条数据
		brm.saveDormOrStudent(saveParams);
		
		return obj;
	}
}
